import React, { useState, useEffect, createContext, FC, MouseEvent } from 'react';
import { Table, Button } from 'antd';
import FilterOptions from './FilterOptions';
import { IPageTableProps } from './interface';
import styles from './index.less';

interface IPageTableContext {
  refreshList?: () => void;
}

export const PageTableContext = createContext<IPageTableContext>({});

const PageTable: FC<IPageTableProps> = props => {
  const {
    total,
    tableList,
    uniqueKey,
    getTableList,
    children,
    pageTitle,
    columns,
    filters = [],
    showCreate,
    createTitle,
    createCallback,
    defaultCondtions = {}
  } = props;

  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchConditons, setSearchConditions] = useState(defaultCondtions);

  useEffect(() => {
    refreshTableList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageNum, pageSize, searchConditons]);

  const refreshTableList = () => {
    getTableList({
      pageNum,
      pageSize,
      ...searchConditons,
    });
  };

  const changePageNumAndSize = ({ num = pageNum, size = pageSize }) => {
    setPageNum(num);
    setPageSize(size);
  };

  const nColumns = columns.map(item => ({
    dataIndex: item.key,
    ...item,
  }));

  const handleSearchConditions = data => {
    setSearchConditions({ ...searchConditons, ...data });
    setPageNum(1);
    setPageSize(10);
  };

  const passedContext = {
    refreshList: refreshTableList,
  };

  return (
    <div className={styles.pageTable}>
      <div className={styles.pageFilters}>
        <div className={styles.filters}>
          <FilterOptions filters={filters} setFilterOpts={handleSearchConditions} />
        </div>

        {showCreate ? (
          <Button type="primary" className={styles.plus} onClick={createCallback}>
            {createTitle}
          </Button>
        ) : null}
      </div>

      <Table
        bordered
        rowKey={record => record[`${uniqueKey}`]}
        columns={nColumns}
        dataSource={tableList}
        pagination={{
          total,
          showQuickJumper: true,
          showTotal: total => `共有${total}条数据满足条件`,
          onChange: (page, pageSize) => changePageNumAndSize({ num: page, size: pageSize }),
          pageSize: 10,
          defaultCurrent: 1,
        }}
      />
      <PageTableContext.Provider value={passedContext}>{children}</PageTableContext.Provider>
    </div>
  );
};

PageTable.defaultProps = {
  filters: [],
  showCreate: false,
  uniqueKey: 'id',
};

export default PageTable;
